﻿namespace KLF.Lib.Browser.DOM.CSS.SAC.Selectors
{
    #region Using Statements

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    #endregion

    internal class SelectorBuilder
    {
        #region Constructors

        internal SelectorBuilder()
        {
            EStack = new List<object>();
        }

        #endregion

        #region Attributes

        internal List<object> EStack { get; set; }

        #endregion

        #region Methods

        internal void Add(object o)
        {
            EStack.Add(o);
        }

        internal Selector Build()
        {
            Selector ret = null;

            if (EStack.Count < 2)
                return (Selector)EStack.First();

            if ((EStack.Count % 2) != 1)
                throw new ArgumentException("Invalid SelectorBuilder state; Must have odd number of elements.");

            for (int i = EStack.Count - 1; i > -1; i --)
            {
                // A + B + C
                if (EStack[i] is String)
                {
                    switch (EStack[i] as String)
                    {
                        case "+":
                            ret = new AdjacentSelector(null, ret);
                            break;

                        case "~":
                            ret = new SiblingSelector(null, ret);
                            break;

                        case ">":
                            ret = new ChildSelector(null, ret);
                            break;

                        case " ":
                            ret = new DescendantSelector(null, ret);
                            break;
                    }
                }
                else if (EStack[i] is Selector)
                {
                    if (ret is BinarySelector)
                    {
                        (ret as BinarySelector).Left = EStack[i] as Selector;
                    }
                    else
                    {
                        ret = EStack[i] as Selector;
                    }
                }
            }

            return ret;
        }

        #endregion
    }
}
